angular.module('baisonShop', ['baisonDb', 'baisonService'])
        //检查店铺是否绑定
        .factory('ShopSetCheck', ['$location', '$rootScope', function ($location, $rootScope) {
                return function () {
                    if (!$rootScope.current_shop) {
                        baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT, buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_INDEX_BIND_SHOP});
                        $location.path('/setting/shop_set');
                        return 1;
                    } else {
                        return;
                    }
                };
            }])
        //获取全部柜台
        .factory('ShopGet', ['apiService', '$q', 'dbReplace', 'dbTrans', function (apiService, $q, dbReplace, dbTrans) {
                var deferred = $q.defer();
                var promise = deferred.promise;
                return function () {
                    var url = 'base/shop/get_list';
                    var data = {'distributor_type': 1, 'fields': 'distributor_code,distributor_name,area_code,brand_code,rebate,use_pd,use_tk'};
                    return apiService(url, data).then(function (ret) {
                        console.log(ret);
                        if (ret.data.status == 1 && ret.data.data.count > 0) {
                            var insert_data = [];
                            $.each(ret.data.data.data, function (i, n) {
                                insert_data.push({
                                    ShopCode: n.distributor_code,
                                    ShopName: n.distributor_name,
                                    AreaCode: n.area_code,
                                    BrandCode: n.brand_code,
                                    Id: n.distributor_code,
                                    ShopRebate :n.rebate, //商店折扣
                                    ShopPriceIndex :n.terminal_price,//商店定价单索引
                                    UsePd:n.use_pd,
                                    UseTk:n.use_tk
                                });
                            });
                            return dbTrans.begin().then(function (success) {
                                return  dbReplace('PosShop', insert_data, ['ShopCode'], ['ShopName', 'AreaCode', 'BrandCode', 'Id','ShopRebate','ShopPriceIndex','UsePd','UseTk']).catch(function (err) {
                                });
                            }).then(function (success) {
                                return dbTrans.commit();
                            }).catch(function (err) {
                                return dbTrans.rollback();
                            });

                        } else {
                            deferred.reject(JSON.stringify(ret.message));
                            return promise;
                        }
                    });
                };
            }])
        //向服务器回传柜台参数
        .factory('ShopSet', ['apiService', '$rootScope', function (apiService, $rootScope) {
                return function () {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var device = baison_app.api.deviceId;
                    return apiService('base/shop/shop_bind', {shop_code: shop_code, device: device, user_code: $rootScope.user.UserCode});
                };
            }])

        //搜索
        .factory('ShopSearch', ['dbSelect', function (dbSelect) {
                return function (keywords) {
                    var sql = 'select * from PosShop where ShopName like "%' + keywords + '%" or ShopCode like "%' + keywords + '%"';
                    return dbSelect('YsPos', sql);
                };
            }])


//        //获取全部柜台

        .factory('ShopGetAll', ['dbSelect', function (dbSelect) {
                return function () {
//                  var sql = 'select * from PosShop where ShopName like "%' + keywords + '%" or ShopCode like "%' + keywords + '%"';
                    var sql = 'select * from PosShop';
                    return dbSelect('YsPos', sql);
                };
            }])
        //获取友好商店
        .factory('ShopGetFriend', ['apiService', '$rootScope', function (apiService, $rootScope) {
                return function () {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('base/shop/get_friend_shop', {shop_code: shop_code});
                };
            }])

        //收银台增删改查
        .factory('shopCashDesk', ['$rootScope', 'dbUpdate', 'apiService', 'dbSelect', 'dbInsert', 'dbDelete', function ($rootScope, dbUpdate, apiService, dbSelect, dbInsert, dbDelete) {
                //获取收银列表
                var getCashList = function (param) {
                    return apiService('base/cash_set/get_list', param);
                };
                //修改
                var CashModify = function (ret) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var data = {
                        cashNum: ret.cashNum,
                        cashName: ret.cashName,
                        remark: ret.remark,
                        shop_code: shop_code
                    };
                    return apiService('base/cash_set/update', data);
                };
                return {
                    getCashList: getCashList,
                    CashModify: CashModify
                };
            }])
        //根据商户代码，获取对应的API地址
        .factory('get_api', ['$rootScope', 'apiService', '$http', function ($rootScope, apiService, $http) {
				var get_api = function (code,password) {
					var data = [];
					data['code'] = code;
					data['password'] = password;
					var post_url = 'http://121.41.36.202/saas_api/?app_act=base/shop/get_api';
					return $http.post(post_url, data).success(function (ret) {});
				};
				return {get_api: get_api};
            }])
        //店铺考勤
        .factory('ShopAttend', ['$rootScope', 'Upload', 'apiService', function ($rootScope, Upload, apiService) {
                //上传考勤数据。 file：待上传文件； date：考勤所属年月
                var configData = $api.getStorage('configData');
                var efast365_key = configData.shanghu;
                var efast365_pass = configData.shanghu_password;
                //var efast365_key = 'baison';
                //var efast365_pass = '123456';

                var datetime = new Date();
                var year = datetime.getFullYear();
                var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
                var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
                var date_str = year + "-" + month + "-" + date;
                var get_sign = function () {
                    var str = efast365_key + efast365_pass + date_str;
                    var sign = $.md5(str);
                    return sign;
                };
                var upload_data = function (file, date) {
                    var configData = $api.getStorage('configData');
                    var url = configData.api_url;
                    var upload_url = url + 'pos/attend/upload';
                    //baison_app.api.alert({msg:upload_url,title:'upload_url'});
//                  var upload_url = 'http://121.41.36.202/api/?app_act=pos/attend/upload';
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var upload_person = $rootScope.user.UserName;
                    var user_code = $rootScope.user.UserCode;
                    var datetime = new Date();
                    var time = parseInt(datetime.getTime() / 1000);
                    var key = configData.shanghu;
                    var sign = get_sign();
                    return Upload.upload({
                        url: upload_url,
                        method: 'POST',
                        file: file,
                        sendFieldsAs: 'form',
                        fields: {
                            'shop_code': shop_code,
                            'date': date,
                            'user_code': user_code,
                            'upload_person': upload_person,
                            'time': time,
                            'key': key,
                            'sign': sign
                        }
                    });
                };
                //从接口获取本店已上传的考勤列表
                var get_list = function () {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code
                    };
                    return apiService('pos/attend/index', filter);
                };
                //
                var shop_status = function (ret, cashier_test) {
                    //cashier_test  1为开始营业  0为结束营业
                    if (cashier_test) {
                        var param = {
                            shop_code: $rootScope.current_shop.ShopCode,
                            cashier_time: ret.cashier_time,
                            start_time: ret.operate_time
                        };
                    } else {
                        var param = {
                            shop_code: $rootScope.current_shop.ShopCode,
                            cashier_time: ret.cashier_time,
                            finish_time: ret.operate_time
                        };
                    }
                    return apiService('base/shop/submit_shop_status', param);
                };
                return {
                    shop_status: shop_status,
                    upload_data: upload_data,
                    get_list: get_list
                };
            }])
        //业绩晴雨表
        .factory('PeFormanceSelect', ['$rootScope', 'apiService', 'timeStamp2String', 'dbUpdate', 'dbSelect', 'dbInsert', 'dbReplace', function ($rootScope, apiService, timeStamp2String, dbUpdate, dbSelect, dbInsert, dbReplace) {
                //从接口获店铺月业绩
                var now = new Date();
                var get_shop_month_indicators = function (date) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/get_month_indicators', filter);
                };
                var get_shop_week_indicators = function (date, end_date) {
                    var date2 = arguments[1] ? arguments[1] : date;
                    var now = new Date();
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date'),
                        date2: timeStamp2String(date2, 'date')
                    };
                    return apiService('base/indicators/get_week_indicators', filter);
                };
                var get_shop_day_indicators = function (date, end_date) {
                    var date2 = arguments[1] ? arguments[1] : date;
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date'),
                        date2: timeStamp2String(date2, 'date')
                    };
                    return apiService('base/indicators/get_day_indicators', filter);
                };
                var get_shop_day_weight = function (date) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/get_weight', filter);
                };

                var get_all_day = function (date) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/get_all_day', filter);
                };
                var set_shop_day_weight = function (date, weight) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var filter = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date'),
                        weight: weight
                    };
                    return apiService('base/indicators/set_shop_day_weight', filter);
                };

                //更新店本月指标
                var update_shop_month_indicators = function (indicators) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        indicators: indicators,
                        date: timeStamp2String(now, 'date')
                    };
                    //baison_app.api.alert({title:"update_shop_month_indicators",msg:params});
                    return apiService('base/indicators/update_shop_month_indicators', params);
                };
                //更新店本周指标
                var update_shop_week_indicators = function (indicators) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        indicators: indicators,
                        date: timeStamp2String(now, 'date')
                    };
                    //baison_app.api.alert({title:"update_shop_week_indicators",msg:params});
                    return apiService('base/indicators/update_shop_week_indicators', params);
                };
                //更新店每周指标
                var update_shop_every_week_indicators = function (indicators) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        indicators: indicators,
                        date: timeStamp2String(now, 'date')
                    };
                    //baison_app.api.alert({title:"update_shop_every_week_indicators",msg:params});
                    return apiService('base/indicators/update_shop_every_week_indicators', params);
                };
                //更新店铺权重
                var update_shop_day_weight = function (weight, date) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        weight: weight,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/set_weight', params);
                };

                var fentan = function (day_weight, date, count) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        day_weight: day_weight,
                        date: timeStamp2String(date, 'date'),
                        count: count
                    };
                    return apiService('base/indicators/fentan', params);
                };
                var get_dianyuan_month_indicators = function (date, user_code) {
                    var _user_code = arguments[1] ? arguments[1] : '';
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date'),
                        user_code: _user_code
                    };
                    return apiService('base/indicators/get_dianyuan_month_indicators', params);
                };
                var save_shop_month_to_dianyuan = function (date, indicators) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        indicators: indicators,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/shop_month_to_dianyuan', params);
                };
                var shop_day_to_dianyuan = function (date, indicators) {
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        indicators: indicators,
                        date: timeStamp2String(date, 'date')
                    };
                    return apiService('base/indicators/shop_day_to_dianyuan', params);
                };
                var get_dianyuan_day_indicators = function (date, date2, user_code) {
                    var _date2 = arguments[1] ? arguments[1] : date;
                    var _user_code = arguments[2] ? arguments[2] : '';
                    var shop_code = $rootScope.current_shop.ShopCode;
                    var params = {
                        shop_code: shop_code,
                        date: timeStamp2String(date, 'date'),
                        date2: timeStamp2String(_date2, 'date'),
                        user_code: _user_code
                    };
                    return apiService('base/indicators/get_dianyuan_day_indicators', params);
                };
                return {
                    get_shop_month_indicators: get_shop_month_indicators,
                    get_shop_week_indicators: get_shop_week_indicators,
                    get_shop_day_indicators: get_shop_day_indicators,
                    update_shop_month_indicators: update_shop_month_indicators,
                    update_shop_week_indicators: update_shop_week_indicators,
                    update_shop_every_week_indicators: update_shop_every_week_indicators,
                    get_shop_day_weight: get_shop_day_weight,
                    update_shop_day_weight: update_shop_day_weight,
                    set_shop_day_weight: set_shop_day_weight,
                    get_all_day: get_all_day,
                    fentan: fentan,
                    get_dianyuan_month_indicators: get_dianyuan_month_indicators,
                    save_shop_month_to_dianyuan: save_shop_month_to_dianyuan,
                    shop_day_to_dianyuan: shop_day_to_dianyuan,
                    get_dianyuan_day_indicators: get_dianyuan_day_indicators
                };

            }])
        ;
